package server;

import server.app.Context;
import server.app.Host;
import server.app.Mapper;
import server.app.Wrapper;

import java.io.InputStream;
import java.net.Socket;
import java.util.Map;

public class RequestProcessor extends Thread{
    private Socket socket;
    private Mapper mapper;

    public RequestProcessor(Socket socket, Mapper mapper) {
        this.socket = socket;
        this.mapper = mapper;
    }

    @Override
    public void run() {
        try {
            InputStream inputStream = socket.getInputStream();
            Request request = new Request(inputStream);
            Response response = new Response(socket.getOutputStream());
            Servlet servlet = getServlet(mapper, request);

            if (null == servlet) {
                response.outputHtml(request.getUrl());
            } else {
                servlet.service(request, response);
            }

            socket.close();

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private Servlet getServlet(Mapper mapper, Request request) {
        String[] split = request.getUrl().split("\\/");
        String context = split[1];
        String servletName = split[2];
        System.out.println(">>>>>>>>>>" + context + ">>>>>>>>>>>>" + servletName);

        for (Host host:
             mapper.getHosts()) {
            if (host.getName().equals(request.getHostAndPort().split(":")[0])) {
                for (Context context1:
                     host.getContexts()) {
                    if (context1.getContextName().equals(context)) {
                        for (Wrapper wrapper:
                             context1.getWrappers()) {
                            if (wrapper.getUrlPattern().equals("/" + servletName)) {
                                return wrapper.getServlet();
                            }
                        }
                    }
                }
            }
        }
        return null;
    }
}
